#!/usr/bin/env python
# encoding: utf-8
"""
TopPage.py

Created by Manabu Terada on 2009-09-21.
Copyright (c) 2009 CMScom. All rights reserved.
"""

from AccessControl import ClassSecurityInfo
from ComputedAttribute import ComputedAttribute
from zope import interface

from Products.Archetypes.atapi import *
from Products.CMFCore.utils import getToolByName

from Products.ATContentTypes.content.document import ATDocument
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.configuration import zconf
from Products.CMFCore.permissions import View, ModifyPortalContent

from c2.site.icos09 import icos09MessageFactory as _
from c2.site.icos09.content.interfaces import ITopPage
from c2.site.icos09.config import *
from c2.site.icos09.swfHeaderData import analyseContent

schema = Schema((
    ImageField('folder_image',
           required=False,
           swallowResizeExceptions = zconf.swallowImageResizeExceptions.enable,
           pil_quality = zconf.pil_config.quality,
           pil_resize_algo = zconf.pil_config.resize_algo,
           max_size = zconf.ATImage.max_image_dimension,
           sizes= {
                   'mini'    :  (480, 480),
                  },
           widget=ImageWidget(label='folder_image',
                              description='',
                              label_msgid='folder_image',
                              description_msgid='folder_image_help',
                              i18n_domain = "icos09"
                              ),
            ),

    IntegerField('flash_h',
        required=False,
        widget=IntegerWidget(label='flash_h',
                        description='',
                        label_msgid='flash_h',
                        description_msgid='flash_h_help',
                        i18n_domain ='icos09',
                        )),
    #
    IntegerField('flash_w',
        required=False,
        widget=IntegerWidget(label='flash_w',
                        description='',
                        label_msgid='flash_w',
                        description_msgid='flash_w_help',
                        i18n_domain ='icos09',
                        )),
    #
    IntegerField('flash_v',
        required=False,
        widget=IntegerWidget(label='flash_v',
                        description='',
                        label_msgid='flash_v',
                        description_msgid='flash_v_help',
                        i18n_domain ='icos09',
                        )),
    # Flashファイル
    FileField('flash',
             required=False,
             searchable=False,
             storage=AnnotationStorage(migrate=True),
             widget=FileWidget(label='flash',
                       description='',
                       label_msgid='flash',
                       description_msgid ='flash_help',
                       i18n_domain='icos09',)),
                       
    # news title
    StringField('news_title',
            required=True,
            searchable=False,
            widget=StringWidget(label='news_title',
                            description='',
                            label_msgid = "news_title",
                            description_msgid = 'news_title_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # news path
    StringField('news_path',
            required=True,
            searchable=False,
            widget=StringWidget(label='news_path',
                            description='',
                            label_msgid = "news_path",
                            description_msgid = 'news_path_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # news count
    IntegerField('news_count',
        required=True,
        widget=IntegerWidget(label='news_count',
                        description='',
                        label_msgid='news_count',
                        description_msgid='news_count_help',
                        i18n_domain ='icos09',
                        )),
    # news link
    StringField('news_link',
            required=True,
            searchable=False,
            widget=StringWidget(label='news_link',
                            description='',
                            label_msgid = "news_link",
                            description_msgid = 'news_link_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # event title
    StringField('event_title',
            required=True,
            searchable=False,
            widget=StringWidget(label='event_title',
                            description='',
                            label_msgid = "event_title",
                            description_msgid = 'event_title_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # event path
    StringField('event_path',
            required=True,
            searchable=False,
            widget=StringWidget(label='event_path',
                            description='',
                            label_msgid = "event_path",
                            description_msgid = 'event_path_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # event count
    IntegerField('event_count',
        required=True,
        widget=IntegerWidget(label='event_count',
                        description='',
                        label_msgid='event_count',
                        description_msgid='event_count_help',
                        i18n_domain ='icos09',
                        )),
    # event link
    StringField('event_link',
            required=True,
            searchable=False,
            widget=StringWidget(label='event_link',
                            description='',
                            label_msgid = "event_link",
                            description_msgid = 'event_link_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    
    # banner path
    StringField('banner_path',
            required=True,
            searchable=False,
            widget=StringWidget(label='banner_path',
                            description='',
                            label_msgid = "banner_path",
                            description_msgid = 'banner_path_help',
                            i18n_domain = "icos09",
                            size=40
                            ),),
    # banner count
    IntegerField('banner_count',
        required=True,
        widget=IntegerWidget(label='banner_count',
                        description='',
                        label_msgid='banner_count',
                        description_msgid='banner_count_help',
                        i18n_domain ='icos09',
                        )),

),)

toppage_schema = getattr(ATDocument, 'schema', Schema(())).copy() + schema.copy()
# toppage_schema['relatedItems'].widget.visible['edit'] = 'invisible'
finalizeATCTSchema(toppage_schema)

class TopPage(ATDocument):
    """
    """
    security = ClassSecurityInfo()
    interface.implements(ITopPage)
    schema = toppage_schema
    
    meta_type = "TopPage"
    _at_rename_after_creation = True

    security.declareProtected(View, 'tag')
    def tag(self, **kwargs):
        """Generate image tag using the api of the ImageField
        """
        kwargs['alt'] = self.image_alt
        return self.getField('folder_image').tag(self, **kwargs)

    security.declareProtected(View, 'getSize')
    def getSize(self, scale=None):
        field = self.getField('folder_image')
        return field.getSize(self, scale=scale)

    security.declareProtected(View, 'getWidth')
    def getWidth(self, scale=None):
        return self.getSize(scale)[0]

    security.declareProtected(View, 'getHeight')
    def getHeight(self, scale=None):
        return self.getSize(scale)[1]

    width = ComputedAttribute(getWidth, 1)
    height = ComputedAttribute(getHeight, 1)

    security.declareProtected(ModifyPortalContent, 'setFlash')
    def setFlash(self, value, **kwargs):
        """Saves file and stores flash informations (size, flash version)"""
        if value and not isinstance(value, str):
            value.seek(0) # rewind
            field=self.getField('flash')
            field.set(self,value,**kwargs)
            value.seek(0)
            tags = analyseContent(value.read(1024))
            self.setFlash_w(tags['width'])
            self.setFlash_h(tags['height'])
            self.setFlash_v(tags['flashversion'])
        elif value and isinstance(value, str):
            field1=self.getField('flash')
            field1.set(self, '', **kwargs)
            self.setFlash_w(0)
            self.setFlash_h(0)
            self.setFlash_v(0)

    security.declareProtected(View, 'get_flash_file')
    def get_flash_file(self, REQUEST=None, RESPONSE=None, *args, **kwargs):
        """Download the file (use default index_html)
        """
        if REQUEST is None:
           REQUEST = self.REQUEST
        if RESPONSE is None:
           RESPONSE = REQUEST.RESPONSE
        RESPONSE.setHeader("Content-Type", "application/x-shockwave-flash")
        field = self.getField('flash')
        return field.get(self, raw=True)
        
registerType(TopPage, PROJECTNAME)

